package com.timesheet.server.core.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import com.timesheet.server.core.emf.EMF;

public class BaseDao {

	private static EntityManager entityManager = EMF.getEntityManager();

	public EntityManager getEntityManager() {
		return entityManager;
	}

	public boolean persist(Object entity) {
		begin();
		entityManager.persist(entity);
		commitAndClose();
		System.out.println("successfully persists object");
		return true;

	}

	public void begin() {
		EntityTransaction transaction = entityManager.getTransaction();
		transaction.begin();
	}

	public void commitAndClose() {
		entityManager.getTransaction().commit();
		//entityManager.close();

	}

	public <T> T find(Class<T> cls, String id) {
		T t = entityManager.find(cls, id);
		return t;
	}
	
	
	public <T> T find(Class<T> cls, int id) {
		T t = entityManager.find(cls, id);
		return t;
	}
	
	
	public <T> T find(Class<T> cls, long id) {
		T t = entityManager.find(cls, id);
		return t;
	}
	
	
	public List getAllObjects(String query){
		
		//begin();
		
		return entityManager.createQuery(query).getResultList();
		
	}

}
